package erfgame.core.graphics.renderer;

import java.util.WeakHashMap;


import erfgame.core.Rotation;
import erfgame.core.entity.Entity;
import erfgame.core.world.World;

public class WeakEntityRendererFactoryProxy 
	implements EntityRendererFactory {

	private World currentWorld;
	private WeakHashMap<Entity, EntityRenderer>[] renderers;
	private EntityRendererFactory proxied;
	
	@SuppressWarnings("unchecked")
	public WeakEntityRendererFactoryProxy( EntityRendererFactory proxied ) {
		this.proxied = proxied;
		this.renderers = new WeakHashMap[4];
		for( int i=0; i<renderers.length; i++ ) {
			this.renderers[i] = new WeakHashMap<Entity, EntityRenderer>();
		}
	}
	
	public EntityRenderer getRenderer(World world, Entity entity, Rotation viewRotation) {
		if( !world.equals( currentWorld ) ) {
			currentWorld = world;
			for( int i=0; i<renderers.length; i++ ) {
				this.renderers[i].clear();				
			}
			// could probably just throw out any renderers not in the current rotation
		}
		EntityRenderer renderer = this.renderers[viewRotation.ordinal()].get( entity );
		if( renderer == null ) {
			renderer = proxied.getRenderer( world, entity, viewRotation );
			this.renderers[viewRotation.ordinal()].put( entity, renderer );
		}
		return renderer;
	}

}
